
package com.shop.cloud.upms.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.core.util.SensitiveUtils;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.annotation.Inside;
import com.shop.cloud.upms.common.entity.SysConfigStorage;
import com.shop.cloud.upms.admin.service.SysConfigStorageService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 存储配置
 *
 * @author 
 * @date 2020-02-03 20:07:38
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/configstorage")
@Tag(description = "configstorage", name = "存储配置管理")
public class SysConfigStorageController {

    private final SysConfigStorageService sysConfigStorageService;

    /**
     * 存储配置修改
     * @param sysConfigStorage 存储配置
     * @return R
     */
	@Operation(summary = "存储配置修改")
    @SysLog("修改存储配置")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('sys:configstorage:edit')")
    public R updateById(@RequestBody SysConfigStorage sysConfigStorage) {
		if(StrUtil.isNotBlank(sysConfigStorage.getId())){
			//数据脱敏
			SysConfigStorage sysConfigStorageOld = sysConfigStorageService.getById(sysConfigStorage.getId());
			String accessKeySecret = sysConfigStorageOld.getAccessKeySecret();
			if(StrUtil.isNotBlank(accessKeySecret)){
				String sensitiveAccessKeySecret = SensitiveUtils.process(accessKeySecret);
				if(!sensitiveAccessKeySecret.equals(sysConfigStorage.getAccessKeySecret())){
					accessKeySecret = sysConfigStorage.getAccessKeySecret();
				}
				sysConfigStorage.setAccessKeySecret(accessKeySecret);
			}

			sysConfigStorageService.updateById(sysConfigStorage);
			return R.ok(sysConfigStorage);
		}else{
			sysConfigStorageService.save(sysConfigStorage);
			return R.ok(sysConfigStorage);
		}
    }

	/**
	 * 查询存储配置
	 * @return R
	 */
	@Operation(summary = "查询存储配置")
	@GetMapping()
	@PreAuthorize("@ato.hasAuthority('sys:configstorage:get')")
	public R get() {
		SysConfigStorage sysConfigStorage = sysConfigStorageService.getOne(Wrappers.emptyWrapper());
		//数据脱敏
		if(sysConfigStorage != null){
			String sensitiveAccessKeySecret = SensitiveUtils.process(sysConfigStorage.getAccessKeySecret());
			sysConfigStorage.setAccessKeySecret(sensitiveAccessKeySecret);
		}

		return R.ok(sysConfigStorage);
	}

	/**
	 * 查询存储配置缓存（服务间调用）
	 * @return R
	 */
	@Inside
	@Operation(summary = "存储配置查询")
	@GetMapping("/inside")
	public R getInside() {
		return R.ok(sysConfigStorageService.getOne());
	}

}
